//
//  RMDetailViewController.m
//  rmplanner
//
//  Created by Andrew Pigram on 3/05/12.
//  Copyright (c) 2012 PiAMP Productions. All rights reserved.
//

#import "RMDetailViewController.h"
#import "RMFirstViewController.h"
#import "RMMeal.h"
#import "RMParser.h"
#import <QuartzCore/QuartzCore.h>

@interface RMDetailViewController ()

@property (strong, nonatomic) UITextField* textField;

@end

typedef enum
{
	Voting,
	OverrideVote,
	Order,
	OverrideOrder
} RequestType;

@implementation RMDetailViewController

static RequestType type;
static BOOL isOneMeal = true;
static NSString* contentStr;

@synthesize mealButton, voteButton, imgView, meal, uid, retData, description, buttonState, allergies, owner, textField;

#pragma mark UIViewController functions

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
		description = [[UITextView alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	// set the navigation bar title to the name of the meal
	description.text = contentStr;
	
	if (!meal.orderable)
	{
		mealButton.hidden = YES;
	}
	else
		mealButton.hidden = NO;
	if (meal.voted)
	{
		[voteButton setTitle:@"Voted" forState:UIControlStateNormal];
		voteButton.enabled = NO;
		voteButton.titleLabel.textColor = [UIColor grayColor];
	}
	else
	{
		[voteButton setTitle:@"Vote" forState:UIControlStateNormal];
		voteButton.enabled = YES;
		voteButton.titleLabel.textColor = [UIColor colorWithRed:.196 green:0.3098 blue:0.52 alpha:1.0];
	}
	if (meal.ordered)
	{
		[mealButton setTitle:@"Ordered" forState:UIControlStateNormal];
		mealButton.enabled = NO;
		mealButton.titleLabel.textColor = [UIColor grayColor];
	}
	else
	{
		[mealButton setTitle:@"Order" forState:UIControlStateNormal];
		mealButton.enabled = YES;
		mealButton.titleLabel.textColor = [UIColor colorWithRed:.196 green:0.3098 blue:0.52 alpha:1.0];
	}
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
		return (interfaceOrientation == UIInterfaceOrientationPortrait);
	else
		return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

#pragma mark Content population/State management functions

- (void)setDetailItem:(RMMeal *)item fromController:(RMFirstViewController *)controller
{
	isOneMeal = YES;
	meal = item;
	self.navigationItem.title = meal.name;
	contentStr = meal.description;
	description.text = meal.description;
	owner = controller;
	
	// following is for iPad only, due to split view controller instance
	if (!meal.orderable)
	{
		mealButton.hidden = YES;
	}
	else
		mealButton.hidden = NO;
	if (meal.voted)
	{
		[voteButton setTitle:@"Voted" forState:UIControlStateNormal];
		voteButton.enabled = NO;
		voteButton.titleLabel.textColor = [UIColor grayColor];
	}
	else
	{
		[voteButton setTitle:@"Vote" forState:UIControlStateNormal];
		voteButton.enabled = YES;
		voteButton.titleLabel.textColor = [UIColor colorWithRed:.196 green:0.3098 blue:0.52 alpha:1.0];
	}
	if (meal.ordered)
	{
		[mealButton setTitle:@"Ordered" forState:UIControlStateNormal];
		mealButton.enabled = NO;
		mealButton.titleLabel.textColor = [UIColor grayColor];
	}
	else
	{
		[mealButton setTitle:@"Order" forState:UIControlStateNormal];
		mealButton.enabled = YES;
		mealButton.titleLabel.textColor = [UIColor colorWithRed:.196 green:0.3098 blue:0.52 alpha:1.0];
	}
}

- (void)setDetailItems:(NSArray *)meals withDate:(NSString *)date
{
	isOneMeal = NO;
	NSMutableString* text = [NSMutableString string];
	for (int i = 0; i < [meals count]; i++)
	{
		[text appendFormat:@"%@ - %@\n\n", ((RMMeal *)[meals objectAtIndex:i]).name, ((RMMeal *)[meals objectAtIndex:i]).description];
	}
	if ([text isEqualToString:@""])
		[text appendString:@"No meals on offer today"];
	contentStr = text;
	self.navigationItem.title = date;
	description.text = contentStr;
}

#pragma mark Interface Builder selectors

- (IBAction)toggleVote
{
	NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/vote"];
	NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setHTTPMethod:@"POST"];
	NSData* data = [[NSString stringWithFormat:@"uid=%d&meal_id=%d",[[NSUserDefaults standardUserDefaults] integerForKey:@"uid"], meal.mealID] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	[request setHTTPBody:data];
	NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
	NSAssert((connection != nil), @"Could not connect to server");
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	type = Voting;
}

- (IBAction)lateMeal
{
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Confirm Order" message:@"Add a comment (optional):" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
	alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
	[alertView show];
}

#pragma mark UIAlertView delegate functions

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	// determine which button was pressed
	if ([alertView.title isEqualToString:@"Success"])
	{
		[owner viewDidLoad];
		return;
	}
	switch (buttonIndex)
	{
		case 1:
			// handle overrides
			if ([alertView.title isEqualToString:@"Dietary Warning"])
			{
				// process an allergy warning
				if (type == Voting)
				{
					type = OverrideVote;
					NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/overrideVote"];
					NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
					NSData* data = [[NSString stringWithFormat:@"uid=%d&meal_id=%d", [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"], meal.mealID] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
					[request setHTTPBody:data];
					NSString* length = [NSString stringWithFormat:@"%d", [data length]];
					[request setValue:length forHTTPHeaderField:@"Content-Length"];
					[request setHTTPMethod:@"POST"];
					NSURLConnection* connection = nil;
					connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
					NSAssert((connection != nil), @"Could not connect");
					[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
				}
				else
				{
					type = OverrideOrder;
					NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/overrideOrder"];
					NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
					NSData* data = [[NSString stringWithFormat:@"uid=%d&meal_id=%d&comment=%@", [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"], meal.mealID, textField.text] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
					[request setHTTPBody:data];
					NSString* length = [NSString stringWithFormat:@"%d", [data length]];
					[request setValue:length forHTTPHeaderField:@"Content-Length"];
					[request setHTTPMethod:@"POST"];
					NSURLConnection* connection = nil;
					connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
					NSAssert((connection != nil), @"Could not connect");
					[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
				}
			}
			else
			{
				// register late meal
				type = Order;
				textField = [alertView textFieldAtIndex:0];
				NSURL* url = [[NSURL alloc] initWithScheme:@"http" host:@"rmplanner.net" path:@"/kitchen/scripts/order"];
				if ([textField.text isEqualToString:@""])
					textField.text = @" ";
				NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
				NSData* data = [[NSString stringWithFormat:@"uid=%d&meal_id=%d&comment=%@", [[NSUserDefaults standardUserDefaults] integerForKey:@"uid"], meal.mealID, textField.text] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
				[request setHTTPBody:data];
				NSString* length = [NSString stringWithFormat:@"%d", [data length]];
				[request setValue:length forHTTPHeaderField:@"Content-Length"];
				[request setHTTPMethod:@"POST"];
				NSURLConnection* connection = nil;
				connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
				NSAssert((connection != nil), @"Could not connect");
				[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
			}
			break;
		default:
			// cancel
			break;
	}
}

#pragma mark NSURLConnection delegate functions

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	retData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	// append the newly downloaded data
	[retData appendData:data];
}

// begin the parsing operation when the URL has completely loaded
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	// process the data
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	connection = nil;
	if (type == Voting)
	{
		NSString* data = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
		if ([data isEqualToString:@"good"])
		{
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Vote registered. You may alter or cancel your vote until the cutoff time" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			[voteButton setTitle:@"Voted" forState:UIControlStateNormal];
			voteButton.enabled = NO;
			voteButton.titleLabel.textColor = [UIColor grayColor];
			meal.voted = YES;
		}
		else if ([data isEqualToString:@"Past the cut-off time for meal voting."])
		{
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Past cut-off" message:@"The cut-off time has passed. Your vote has not been registered." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
		}
		else
		{
			// parse the allergies
			RMParser* parser = [[RMParser alloc] init];
			NSLog(@"%@", data);
			[parser specialParse:retData controller:self];
			NSMutableString* warning = [NSMutableString stringWithString:@"You have indicated warnings for the following ingredients:\n"];
			for (int i = 0; i < [allergies count]; i++)
			{
				[warning appendFormat:@"%@\n", [allergies objectAtIndex:i]];
			}
			[warning appendString:@"Are you sure you wish to proceed?"];
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Dietary Warning" message:warning delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
			[alertView show];
		}
	}
	else if (type == OverrideVote)
	{
		NSString* data = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
		if ([data isEqualToString:@"good"])
		{
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Vote registered. You may alter or cancel your vote until the cutoff time" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			[voteButton setTitle:@"Voted" forState:UIControlStateNormal];
			voteButton.enabled = NO;
			voteButton.titleLabel.textColor = [UIColor grayColor];
			meal.voted = YES;
		}
		else if ([data isEqualToString:@"Past the cut-off time for meal voting."])
		{
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Past cut-off" message:@"The cut-off time has passed. Your vote has not been registered." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
		}
		else
		{
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Vote not registered.Please try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
		}
	}
	else if (type == Order)
	{
		NSString* data = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
		NSLog(@"%@", data);
		if ([data isEqualToString:@"good"])
		{
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Order registered. You may alter or cancel your order until the cutoff time" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			[mealButton setTitle:@"Ordered" forState:UIControlStateNormal];
			mealButton.enabled = NO;
			mealButton.titleLabel.textColor = [UIColor grayColor];
			meal.ordered = YES;
		}
		else if ([data isEqualToString:@"Past the cut-off time for meal ordering."])
		{
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Past cut-off" message:@"The cut-off time has passed. Your order has not been registered." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
		}
		else
		{
			// parse the allergies
			RMParser* parser = [[RMParser alloc] init];
			NSLog(@"%@", data);
			[parser specialParse:retData controller:self];
			NSMutableString* warning = [NSMutableString stringWithString:@"You have indicated warnings for the following ingredients:\n"];
			for (int i = 0; i < [allergies count]; i++)
			{
				[warning appendFormat:@"%@\n", [allergies objectAtIndex:i]];
			}
			[warning appendString:@"Are you sure you wish to proceed?"];
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Dietary Warning" message:warning delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
			[alertView show];
		}
	}
	else
	{
		NSString* data = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
		if ([data isEqualToString:@"good"])
		{
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Order registered. You may alter or cancel your order until the cutoff time" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			[mealButton setTitle:@"Ordered" forState:UIControlStateNormal];
			mealButton.enabled = NO;
			mealButton.titleLabel.textColor = [UIColor grayColor];
			meal.ordered = YES;
		}
		else if ([data isEqualToString:@"Past the cut-off time for meal ordering."])
		{
			UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Past cut-off" message:@"The cut-off time has passed. Your order has not been registered." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alertView show];
		}
		else
		{
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Order not registered. Please try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
		}
	}
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	NSLog(@"%@", [error description]);
	connection = nil;
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Connection Error" message:@"Connection to server failed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alertView show];
}

#pragma mark UITextViewDelegate functions

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
	[textView resignFirstResponder];
	return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
	textView.text = @"";
}

@end
